﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Linq;

using System.Threading;

using CG.Security;
using CG.Security.Principal;



namespace td.Core.Security
{
    public partial class UserManagerForm : DevExpress.XtraEditors.XtraUserControl,IToolButton
    {
        List<User> list = new List<User>();
        DataTable roles, users;
        Dictionary<int, string> roleDic;
        td.Core.Controls.tdGridView<User> gridControl1 = new Controls.tdGridView<User>();
        public UserManagerForm()
        {
            InitializeComponent();
            this.panelControl2.Controls.Add(gridControl1);
            gridControl1.Dock = DockStyle.Fill;
            InitGridView();
            BindData();

            roles = RoleManager.FindAll().Tables[0];
            roleDic = new Dictionary<int, string>();
            for (int i = 0; i < roles.Rows.Count; i++)
            {
                int id = int.Parse(roles.Rows[i]["role_id"].ToString());
                roleDic.Add(id, roles.Rows[i]["role_name"].ToString());
            }
            this.cbRoleName.Properties.Items.Add("");
            var e = roleDic.GetEnumerator();
            while (e.MoveNext())
            {
                this.cbRoleName.Properties.Items.Add(e.Current.Value);
            }
            this.gridControl1.gridView1.RowCellClick += new DevExpress.XtraGrid.Views.Grid.RowCellClickEventHandler(gridView1_RowCellClick);
            
        }

        void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left && e.Clicks > 1)
            {
                User u = new User();
                u.id = int.Parse(this.gridControl1.gridView1.GetRowCellDisplayText(e.RowHandle, "id"));
                u.name = this.gridControl1.gridView1.GetRowCellDisplayText(e.RowHandle, "name");
                u.logindate = this.gridControl1.gridView1.GetRowCellDisplayText(e.RowHandle, "logindate");
                u.createdate = this.gridControl1.gridView1.GetRowCellDisplayText(e.RowHandle, "createdate");
                td.Core.Security.UserInfo userinfo = new UserInfo(u);
                userinfo.ShowDialog(this);
            }
        }

        /// <summary>
        /// 获取当前在列表中选中的用户
        /// </summary>
        /// <returns>userID</returns>
        public int  GetSelectedUser()
        {
            var rowindex = this.gridControl1.gridView1.FocusedRowHandle;
            return this.list[rowindex].id;
        }
        public void BindData()
        {           
            users = UserManager.FindAll().Tables[0];
            list.Clear();
            for (int i = 0; i < users.Rows.Count; i++)
            {
                list.Add(new User()
                {
                    id = int.Parse(users.Rows[i]["user_id"].ToString()),
                    name = users.Rows[i]["user_name"].ToString(),
                    createdate = users.Rows[i]["create_date"].ToString(),
                    logindate = users.Rows[i]["last_login"].ToString(),
                    //roleid = UserRoleDic[int.Parse(users.Rows[i]["user_id"].ToString())],
                    //rolename = roleDic[UserRoleDic[int.Parse(users.Rows[i]["user_id"].ToString())]]
                });
            }
            this.gridControl1.DataSource = list.AsQueryable<User>(); 
        }
        private void InitGridView()
        {
            this.gridControl1.DisplayColumns = "id,name,createdate,logindate";
            this.gridControl1.NonDisplayColumns = "id";
            this.gridControl1.AddColumnAlias("name", "用户名");
            this.gridControl1.AddColumnAlias("createdate", "创建日期");
            this.gridControl1.AddColumnAlias("logindate", "最后登录日期");
            this.gridControl1.gridView1.OptionsBehavior.Editable = false;
        }

       
        /// <summary>
        /// 角色组合框变化 ，以角色查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbRoleName_SelectedIndexChanged(object sender, EventArgs e)
        {
            SerachUsers();
        }

        private void SerachUsers()
        {
            if (this.cbRoleName.Text != null && this.cbRoleName.Text != "")
            {
                var t = CG.Security.RoleManager.FindAll().Tables[0];
                int roleid = 0;
                for (int i = 0; i < t.Rows.Count; i++)
                {
                    if (t.Rows[i]["role_name"].ToString() == this.cbRoleName.Text.Trim())
                    {
                        roleid = (int)t.Rows[i]["role_id"];
                        break;
                    }
                }
                var userrole = CG.Security.UserRoleManager.FindByRole(roleid).Tables[0];
                Dictionary<int, int> userInrole = new Dictionary<int, int>();
                for (int i = 0; i < userrole.Rows.Count; i++)
                {
                    userInrole.Add((int)userrole.Rows[i]["user_id"], (int)userrole.Rows[i]["user_id"]);
                }
                var c = list.Where(p => userInrole.Keys.Contains(p.id) && p.name.Contains(this.tbUserName.Text));
                this.gridControl1.DataSource = c.AsQueryable<User>();
            }
            else
            {
                var c = list.Where(p => p.name.Contains(this.tbUserName.Text));
                this.gridControl1.DataSource = c.AsQueryable<User>();
            }
        }

        private void tbUserName_TextChanged(object sender, EventArgs e)
        {
            SerachUsers();
        }


        public void OnNew()
        {
            AddUser adduser = new AddUser();
            if (adduser.ShowDialog() == DialogResult.OK)
            {
                CG.Security.UserManager.Create(adduser.UserName, adduser.Password);
                this.BindData();
            }
        }

        public void OnSave()
        {
            
        }

        public void OnSaveAs()
        {
           
        }

        public void OnDelete()
        {
            
        }
    }
}

